package common.activiti.web.action;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.IdentityService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Attachment;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import common.security.web.util.SecurityUtil;
import common.web.vo.Result;

/**
 * 附件控制器
 *
 */
@Controller
@RequestMapping(value = "/bpm/attachment")
public class AttachmentController {

	@Autowired
	TaskService taskService;

	@Autowired
	IdentityService identityService;

	/**
	 * 文件类型的附件
	 */
	@RequestMapping(value = "new/file")
	@ResponseBody
	public Result newFile(@RequestParam("taskId") String taskId,
			@RequestParam(value = "processInstanceId", required = false) String processInstanceId,
			@RequestParam("attachmentName") String attachmentName,
			@RequestParam(value = "attachmentDescription", required = false) String attachmentDescription,
			@RequestParam("file") MultipartFile file, HttpSession session) {
		try {
			String attachmentType = file.getContentType() + ";"
					+ FilenameUtils.getExtension(file.getOriginalFilename());
			identityService.setAuthenticatedUserId(SecurityUtil.getUserName());
			Attachment attachment = taskService.createAttachment(attachmentType, taskId, processInstanceId,
					attachmentName, attachmentDescription, file.getInputStream());
			taskService.saveAttachment(attachment);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Result.SUCCESS;
	}

	/**
	 * URL类型的附件
	 */
	@RequestMapping(value = "new/url")
	@ResponseBody
	public Result newUrl(@RequestBody JSONObject json) {

		String taskId = json.getString("taskId");
		if (StringUtils.isBlank(taskId)) {
			return Result.fail("任务ID不能为空");
		}
		String processInstanceId = json.getString("processInstanceId");
		if (StringUtils.isBlank(processInstanceId)) {
			return Result.fail("实例ID不能为空");
		}
		String attachmentName = json.getString("attachmentName");
		if (StringUtils.isBlank(attachmentName)) {
			return Result.fail("附件名不能为空");
		}
		String attachmentDescription = json.getString("attachmentDescription");
		String url = json.getString("url");
		if (StringUtils.isBlank(attachmentName)) {
			return Result.fail("URL不能为空");
		}

		String attachmentType = "url";
		identityService.setAuthenticatedUserId(SecurityUtil.getUserName());
		/* Attachment attachment = */
		taskService.createAttachment(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription,
				url);
		/*
		 * 如果要更新附件内容，先读取附件对象，然后设置属性（只能更新name和description），最后保存附件对象
		 */
		// taskService.saveAttachment(attachment);
		return Result.SUCCESS;
	}

	/**
	 * 删除附件
	 */
	@RequestMapping(value = "delete/{attachmentId}")
	@ResponseBody
	public Result delete(@PathVariable("attachmentId") String attachmentId) {
		identityService.setAuthenticatedUserId(SecurityUtil.getUserName());
		taskService.deleteAttachment(attachmentId);
		return Result.SUCCESS;
	}

	/**
	 * 下载附件
	 *
	 * @throws IOException
	 */
	@RequestMapping(value = "download/{attachmentId}")
	public void downloadFile(@PathVariable("attachmentId") String attachmentId, HttpServletResponse response)
			throws IOException {
		Attachment attachment = taskService.getAttachment(attachmentId);
		InputStream attachmentContent = taskService.getAttachmentContent(attachmentId);
		String contentType = StringUtils.substringBefore(attachment.getType(), ";");
		response.addHeader("Content-Type", contentType + ";charset=UTF-8");
		String extensionFileName = StringUtils.substringAfter(attachment.getType(), ";");
		String fileName = attachment.getName() + "." + extensionFileName;
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		IOUtils.copy(new BufferedInputStream(attachmentContent), response.getOutputStream());
	}
}
